package main

import (
	"fmt"
	"iot-base/common/cache"
	_ "iot-base/common/ctrl"
	"iot-base/common/ctrltype"
	"iot-base/common/dbconn"
	"iot-base/common/notify"
	"iot-base/common/params"
	"sync"
	"time"
	//"sync"
)

type meteID struct {
	pid string
	sid string
	//ctrlName string
	status int
}

var doorOpenMete = [...]meteID{meteID{pid: "IO status", sid: "door"}, meteID{pid: "key1", status: 0},
	meteID{pid: "key2", status: 2}, meteID{pid: "key3", status: 1}}

const doorModelID = "m_HHlL0VNGsKPldkrvOAtMR"
const ipcModelID = "m_SlTrLORmaPXHeS3Xrocpz"
const ctrlBoardModelID = "m_tLcsjBdvEy1og2tn2PkTx"

func init() {

}

var lightState [4]bool

func light(doorId string, doorIndex int, isOpen bool) { //开门开灯
	fmt.Println("openlight-----------------", doorId, doorIndex, isOpen)
	lightId := getCtrlId(doorId, ctrlBoardModelID)
	//var runCount = 0
	params := make(map[string]interface{})

	var ctrlCmd ctrltype.CtrlCmd
	ctrlCmd.Params = params

	ctrlCmd.ThingID = lightId
	//splashLightOld := lightState[1]
	lightState[doorIndex] = isOpen
	//var isOK bool = false
	//if splashLightOld != lightState[1] { //2号门是频闪灯，频闪灯控制使用light2_crl
	if lightState[1] {
		params["value"] = "1"
	} else {
		params["value"] = "0"
	}
	ctrlCmd.ID = "light2_crl"
	for i := 0; i < 3; i++ {
		//var wg sync.WaitGroup
		//wg.Add(1)
		isOK := false
		notify.Ctrl(&ctrlCmd, time.Second*2, func(pResult *ctrltype.CtrlResult) {
			if pResult != nil {
				if pResult.Error == nil {
					fmt.Println("open light ctrl ok:", ctrlCmd)
					isOK = true
				} else {
					fmt.Println("open light ctrl err:", ctrlCmd, pResult)
				}
			}
			//wg.Add(-1)
		}, true)
		//wg.Wait()
		if isOK {
			break
		}
	}
	//}
	var status = 0
	for i, state := range lightState {
		if i < 2 { //从3号灯（索引2）开始使用delay_control控制
			continue
		}
		if state {
			status += doorOpenMete[i].status
		}
	}

	//if status != curCode {
	//curCode = status
	ctrlCmd.ID = "delay_control"
	params["word"] = fmt.Sprintf("%d", status)
	params["ID"] = "4"
	delete(params, "value")
	fmt.Println("open light ctrl:", ctrlCmd)
	isOK := false
	for i := 0; i < 3; i++ {
		//var wg sync.WaitGroup
		//wg.Add(1)
		notify.Ctrl(&ctrlCmd, time.Second*2, func(pResult *ctrltype.CtrlResult) {
			if pResult != nil {
				if pResult.Error == nil {
					fmt.Println("open light ctrl ok:", ctrlCmd)
					isOK = true
				} else {
					fmt.Println("open light ctrl err:", ctrlCmd, pResult)
				}
			}
			//wg.Add(-1)
		}, true)
		//wg.Wait()
		if isOK {
			break
		}
	}
	//}

}
func getDoorIndex(pid, sid string) (bool, int) {
	for i, meteId := range doorOpenMete {
		if meteId.pid == pid && meteId.sid == sid {
			return true, i
		}
	}
	return false, -1
}
func getCtrlId(doorId string, modelId string) string {
	pThing, _ := cache.GetThing(doorId)
	if pThing != nil {
		stationID := pThing.StationID
		if stationID != "" {
			var ipcId string
			dbconn.DBConnection.Raw(`select uid from things,thing_stations where things.uid = thing_stations.thing_id
			and thing_stations.station_id = ? and things.model_id =? `, stationID, modelId).First(&ipcId)
			return ipcId
		}
	}
	return ""
}

func snap(doorId string) {
	ipcId := getCtrlId(doorId, ipcModelID)
	for i := 0; i < 3; i++ {
		fmt.Println("snap---------------------")
		if ipcId != "" {
			params := make(map[string]interface{})
			params["profile"] = "000"
			var ctrlCmd ctrltype.CtrlCmd
			ctrlCmd.Params = params
			ctrlCmd.ID = "snap"
			ctrlCmd.ThingID = ipcId
			notify.Ctrl(&ctrlCmd, 0, nil, false)
			time.Sleep(time.Second * 2)
		}
	}
}
func main() {
	wg := sync.WaitGroup{}
	wg.Add(1)
	notify.SubDataReady(func(pValue *params.ValueInRedis) {

			if pValue.ModelID == doorModelID || pValue.ModelID == ctrlBoardModelID {
				isFound, index := getDoorIndex(pValue.PID, pValue.SID)
				fmt.Println("found door sate changed--------", isFound, index, pValue.ModelID)
				if isFound {
				if index == 0 && pValue.IValue == 1 && pValue.IsChanged {
						go snap(pValue.TID)
					}
				if index >= 1 {
					fmt.Println("light--------", pValue.TID, index, pValue.IValue == 1)
						go light(pValue.TID, index, pValue.IValue == 1)
					}

				}
			}

	})
	wg.Wait()
}
